package bank.driver.sockets;

import java.io.IOException;
import java.net.UnknownHostException;

import bank.Account;
import bank.InactiveException;
import bank.OverdrawException;
import bank.server.sockets.Response;
import bank.server.sockets.account.*;

public class SocketAccount implements Account {

	private String owner;
	private String number;
	
	private SocketMessenger messenger;
	
	public SocketAccount(String owner, String number, SocketMessenger messenger){
		this.owner = owner;
		this.number = number;
		this.messenger = messenger;
	}

	/**
	 * "einzahlen"
	 */
	@Override
	public void deposit(double amount) throws IOException, 
	                                          IllegalArgumentException,
	                                          InactiveException {
		Response resp = this.messenger.send(new DepositRequest(number, amount));
		if (resp instanceof DepositResponse) {
			Exception e = ((DepositResponse)resp).getException();
			if (e instanceof IllegalArgumentException) {
				throw (IllegalArgumentException)e;
			}
			else if (e instanceof InactiveException) {
				throw (InactiveException)e;
			}
		} else {
			throw new IOException();
		}
	}

	@Override
	public double getBalance() throws IOException {
		Response resp = this.messenger.send(new GetBalanceRequest(number));
		if (resp instanceof GetBalanceResponse) {
			return ((GetBalanceResponse)resp).getBalance();
		}
		throw new IOException();
	}

	@Override
	public String getNumber() throws IOException {
		return this.number;
	}

	@Override
	public String getOwner() throws IOException {
		return this.owner;
	}

	@Override
	public boolean isActive() throws IOException {
		Response resp = this.messenger.send(new IsActiveRequest(number));
		if (resp instanceof IsActiveResponse) {
			return ((IsActiveResponse)resp).getStatus();
		}
		throw new IOException();
	}

	/**
	 * "abheben"
	 */
	@Override
	public void withdraw(double amount) throws IOException,
	                                           IllegalArgumentException,
	                                           OverdrawException,
	                                           InactiveException {
		Response resp = this.messenger.send(new WithdrawRequest(number, amount));
		if (resp instanceof WithdrawResponse){
			Exception e = ((WithdrawResponse)resp).getException();
			if (e instanceof IllegalArgumentException) {
				throw (IllegalArgumentException)e;
			}
			else if (e instanceof InactiveException) {
				throw (InactiveException)e;
			}
			else if (e instanceof OverdrawException) {
				throw (OverdrawException)e;
			}
		} else {
			throw new IOException();
		}
	}

	protected void deactivate() {
		try {
			this.messenger.send(new DeactivateRequest(number));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
